//javascript:
function main() {
	url = window.location.href;
	if (url.indexOf('screen=place') == -1)
		alert('This script needs to be run from the rally point');
	else {
		var regex = new RegExp("[\\?&]village=([^&#]*)");
		var results = regex.exec(window.location.href);
		village = results[1];
		$.get(window.location.href, {village: village, screen: "overview"}, function(data) {
			var ind1 = data.indexOf('[' + 'farming]');
			var ind2 = data.indexOf('[/' + 'farming]');
			var list = data.substring(ind1 + 9, ind2).split('<br />');
			var filtered = new Array();
			for( var i = 0; i < list.length; i++)
				if($.trim(list[i]).length > 0)
					filtered.push($.trim(list[i]));
			
			var doc = document;
			
			if(window.frames.length > 0)
				doc = window.main.document;
			
			var index = 0;
			farmcookie = doc.cookie.match('(^|;) ?farm' + village + '=([^;]*)(;|$)');
			if(farmcookie != null)
				index = parseInt(farmcookie[2]);
			
			if(index >= filtered.length)
				alert('last village');
			
			if(index >= filtered.length)
				index = 0;
			
			var command = filtered[index];
			command = command.split(',');
			var coords = command[0].split("|");
			var haul = command[1];
			var previndex = index;
			index = index + 1;
			var cookie_date = new Date(2099, 11, 11);
			document.cookie = "farm" + village + "=" + index + ";expires=" + cookie_date.toGMTString();
			
			$("#units_form input[name=x]").val(coords[0]);
			$("#units_form input[name=y]").val(coords[1]);
			var maxspear = eval($("#unit_input_spear").next().html());
			var maxaxe = eval($("#unit_input_axe").next().html());
			var maxlc = eval($("#unit_input_light").next().html());
			var maxspy = eval($("#unit_input_spy").next().html());
			var axes = Math.max(Math.ceil(haul / (maxspear / maxaxe * 25 + 10)), 8);
			
			if(axes < maxaxe) {
				haul -= axes * 10;
				spears = Math.ceil(haul / 25);
				lc = 0;
			} else {
				axes = 0;
				spears = 0;
				lc = Math.ceil(haul / 80);
				if (lc > maxlc)
					lc = maxlc;
			}
			
			insertUnit($('#unit_input_spear'), spears);
			insertUnit($('#unit_input_axe'), axes);
			insertUnit($('#unit_input_spy'), Math.min(maxspy, 1));
			insertUnit($('#unit_input_light'), lc);
			
			if(index >= filtered.length)
				index = 0;
			
			nextcommand = filtered[index];
			nextcommand = nextcommand.split(',');
			nexthaul = nextcommand[1];
			infodiv = document.createElement("DIV");
			infodiv.appendChild(document.createTextNode('Haul(' + (previndex + 1) + '/' + filtered.length + ') Next Haul(' + (index + 1) + '/' + filtered.length + '): ' + nexthaul));
			doc.forms[0].appendChild(infodiv);
		});
	}
}
main();